package com.yunti.yntk.activity.stepper;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.*;
import android.widget.*;
import androidx.appcompat.widget.LinearLayoutCompat;
import com.google.android.material.textfield.TextInputEditText;
import com.yunti.yntk.R;
import com.yunti.yntk.activity.BaseActivity;
import com.yunti.yntk.activity.batchRecord.BatchRecordActivity;
import com.yunti.yntk.callback.PointPositionCallBack;
import com.yunti.yntk.manager.ComputScoreManager;
import com.yunti.yntk.manager.TotalStationManager;
import com.yunti.yntk.model.PointPosition;
import com.yunti.yntk.util.AngleUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

public class StepperActivity_ty extends BaseActivity implements View.OnClickListener, PointPositionCallBack {

    TextView step1Icon;
    TextView step1Text;
    TextView step2Icon;
    TextView step2Text;
    TextView step3Icon;
    TextView step3Text;
    TextView originaltext;
    TextView stepperTittle;
    LinearLayoutCompat steppercontent;
    Button prebutton;
    Button nextbutton;
    Spinner modeSpinner;
    int pageindex = 1;
    int selectColor = Color.BLACK;
    int disselectColor = Color.GRAY;
    int mode;

    TextView resultValue;

    View step1;
    View step2_1;
    View step2_2;
    View step2_3;
    View step3;
    TextView hr_value;
    Button makezro;
    Button startSurvey;

    TextView ahr_value;
    TextView ahd_value;
    TextView bhr_value;
    TextView bhd_value;

    Button startSurveyA;
    Button confirmA;
    Button startSurveyB;
    Button confirmB;

    boolean aisconfirm = false;
    boolean bisconfirm = false;

    TextInputEditText constant;

    PointPosition aPoint = new PointPosition();
    PointPosition bPoint = new PointPosition();

    Spinner edmSpinner;
    private Integer subId;
    private String gameName;

    private int type;

//    Button update;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stepper);
        initdata();
        initview();
    }

    @Override
    public int initLayoutId() {
        return R.layout.activity_stepper;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() throws IOException {
        Intent intent = getIntent();
        gameName = intent.getStringExtra("gameName");
        subId = intent.getIntExtra("subId",0);
        type = intent.getIntExtra("type",1);
    }

    void initdata() {
        ComputScoreManager.getInstance().setConstant(0);
        TotalStationManager.getInstance().setPointPositionCallBack(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    void initview() {
        step1Icon = findViewById(R.id.step1icon);
        step2Icon = findViewById(R.id.step2icon);
        step3Icon = findViewById(R.id.step3icon);

        step1Text = findViewById(R.id.step1text);
        step2Text = findViewById(R.id.step2text);
        step3Text = findViewById(R.id.step3text);
        steppercontent = findViewById(R.id.steppercontent);
        prebutton = findViewById(R.id.prebutton);
        prebutton.setOnClickListener(this);
        nextbutton = findViewById(R.id.nextbutton);
        nextbutton.setOnClickListener(this);

        edmSpinner = findViewById(R.id.edmSpanner);
//        edmSpinner.setSelection((int)TotalStationApi.getInstance().edm);
        edmSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TotalStationManager.getInstance().setEdm(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        constant = findViewById(R.id.constant);
        constant.setText(ComputScoreManager.getInstance().getConstant() + "");
        constant.addTextChangedListener(new TextWatcher() {
            //编辑框的内容发生改变之前的回调方法
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            //编辑框的内容正在发生改变时的回调方法 >>用户正在输入
            //我们可以在这里实时地 通过搜索匹配用户的输入
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            //编辑框的内容改变以后,用户没有继续输入时 的回调方法
            @Override
            public void afterTextChanged(Editable s) {
                String input = s.toString();
                try {
                    ComputScoreManager.getInstance().setConstant(Double.parseDouble(input));
                } catch (RuntimeException exception) {
                    exception.printStackTrace();
                    ComputScoreManager.getInstance().setConstant(0);
                }
            }
        });


        buildstep1();
        buildstep2_1();
        buildstep2_2();
//        buildstep2_3();
        buildstep3();
        addstep1();

    }

    void buildstep1() {
        step1 = LayoutInflater.from(this).inflate(R.layout.fragment_step1, null);
        modeSpinner = step1.findViewById(R.id.modeselect);
        if (ComputScoreManager.getInstance().getGamemode() != ComputScoreManager.QQ
                && ComputScoreManager.getInstance().getGamemode() != ComputScoreManager.BQ
                && ComputScoreManager.getInstance().getGamemode() != ComputScoreManager.TB
                && ComputScoreManager.getInstance().getGamemode() != ComputScoreManager.LQ) {
            modeSpinner.setSelection(ComputScoreManager.getInstance().getGamemode() - 1);
        }
        modeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                mode = pos;
                if (pos == 0) ComputScoreManager.getInstance().setGamemode(ComputScoreManager.TY_1);
                if (pos == 1) ComputScoreManager.getInstance().setGamemode(ComputScoreManager.TY_2);
                if (pos == 2) ComputScoreManager.getInstance().setGamemode(ComputScoreManager.TY_3);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
        ;
    }

    void buildstep2_1() {
        step2_1 = LayoutInflater.from(this).inflate(R.layout.fragment_step2, null);
        hr_value = step2_1.findViewById(R.id.HR_value);
        makezro = step2_1.findViewById(R.id.makezero);
        makezro.setOnClickListener(this);
    }

    void buildstep2_2() {
        step2_2 = LayoutInflater.from(this).inflate(R.layout.fragment_step2_2, null);
        ahr_value = step2_2.findViewById(R.id.a_hr);
        ahd_value = step2_2.findViewById(R.id.a_hd);
        bhr_value = step2_2.findViewById(R.id.b_hr);
        bhd_value = step2_2.findViewById(R.id.b_hd);

        stepperTittle = step2_2.findViewById(R.id.steppertittle);

        startSurveyA = step2_2.findViewById(R.id.startSurveyA);
        startSurveyA.setOnClickListener(this);
        startSurveyB = step2_2.findViewById(R.id.startSurveyB);
        startSurveyB.setOnClickListener(this);
        confirmA = step2_2.findViewById(R.id.confirmA);
        confirmA.setOnClickListener(this);
        confirmB = step2_2.findViewById(R.id.confirmB);
        confirmB.setOnClickListener(this);
    }


    void buildstep3() {
        step3 = LayoutInflater.from(this).inflate(R.layout.fragment_step3, null);
        startSurvey = step3.findViewById(R.id.startSurvey);
        resultValue = step3.findViewById(R.id.scoretext);
        startSurvey.setOnClickListener(this);

        originaltext = step3.findViewById(R.id.originaldata);
//        update = step3.findViewById(R.id.update);
//        update.setOnClickListener(this);
    }

    void addstep1() {
        step1Text.setTextColor(selectColor);
        step2Text.setTextColor(disselectColor);
        step3Text.setTextColor(disselectColor);

        step1Icon.setText("1");
        step2Icon.setText("2");
        step3Icon.setText("3");
        if (steppercontent.getChildCount() > 1) steppercontent.removeViewAt(0);
        steppercontent.addView(step1, 0);
    }

    void addstep2() {
        step1Text.setTextColor(disselectColor);
        step2Text.setTextColor(selectColor);
        step3Text.setTextColor(disselectColor);

        step1Icon.setText("✔");
        step2Icon.setText("2");
        step3Icon.setText("3");
        if (steppercontent.getChildCount() > 1) steppercontent.removeViewAt(0);
        if (mode == 0) {
            steppercontent.addView(step2_1, 0);
        } else if (mode == 1) {

            steppercontent.addView(step2_2, 0);
            stepperTittle.setText("1.将仪器置于起跳线之前");
        } else {
            stepperTittle.setText("1.将仪器置于起跳线之后");
            steppercontent.addView(step2_2, 0);

        }
    }

    void addstep3() {
        step1Text.setTextColor(disselectColor);
        step2Text.setTextColor(disselectColor);
        step3Text.setTextColor(selectColor);

        step1Icon.setText("✔");
        step2Icon.setText("✔");
        step3Icon.setText("3");
        if (steppercontent.getChildCount() > 1) steppercontent.removeViewAt(0);
        steppercontent.addView(step3, 0);
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.prebutton: {
                if (pageindex == 1) return;
                pageindex--;
                if (pageindex == 1) addstep1();
                if (pageindex == 2) addstep2();
                break;
            }
            case R.id.nextbutton: {
                if (pageindex == 3) {
                    Intent intent = new Intent(this, BatchRecordActivity.class);
                    intent.putExtra("subId", subId);
                    intent.putExtra("subName", gameName);
                    intent.putExtra("type", type);
                    startActivity(intent);
                    this.finish();
                    return;
                }
                pageindex++;
                if (pageindex == 2) {
                    addstep2();
                }
                if (pageindex == 3) {
                    if (mode == 1 || mode == 2) ComputScoreManager.getInstance().computeH();
                    ComputScoreManager.getInstance().saveParameter();
                    addstep3();
                }
                break;
            }
            case R.id.startSurvey:
                new Thread() {
                    public void run() {
                        PointPosition result = TotalStationManager.getInstance().getPoint();
                        double score = ComputScoreManager.getInstance().getScore(result);
                        String originaldata = ComputScoreManager.getInstance().getOriginaldata(result);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                resultValue.setText(score + "m");
                                originaltext.setText(originaldata);
                            }
                        });
                    }
                }.start();  //开启一个线程
                break;
            case R.id.makezero:
                TotalStationManager.getInstance().makeZero();
                break;
            case R.id.startSurveyA:
                new Thread() {
                    public void run() {
                        TotalStationManager.getInstance().makeZero();
                        PointPosition result = TotalStationManager.getInstance().getPoint();
                        aPoint = result;
                        aisconfirm = false;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ahr_value.setTextColor(Color.RED);
                                ahd_value.setTextColor(Color.RED);
                                ahr_value.setText(AngleUtils.changeToDFMArray(result.getAngle()) + "度");
                                ahd_value.setText(result.getDistance() + "米");
                            }
                        });
                    }
                }.start();  //开启一个线程
                break;
            case R.id.startSurveyB:
                new Thread() {
                    public void run() {
                        PointPosition result = TotalStationManager.getInstance().getPoint();
                        bPoint = result;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                bhr_value.setTextColor(Color.RED);
                                bhd_value.setTextColor(Color.RED);
                                bhr_value.setText(AngleUtils.changeToDFMArray(result.getAngle()) + "度");
                                bhd_value.setText(result.getDistance() + "米");
                            }
                        });
                    }
                }.start();  //开启一个线程
                break;
            case R.id.confirmA:
                aisconfirm = true;
                ComputScoreManager.getInstance().setaPoint(aPoint);
                ahr_value.setTextColor(Color.GREEN);
                ahd_value.setTextColor(Color.GREEN);
                break;
            case R.id.confirmB:
                bisconfirm = true;
                ComputScoreManager.getInstance().setbPoint(bPoint);
                bhr_value.setTextColor(Color.GREEN);
                bhd_value.setTextColor(Color.GREEN);
                break;
//            case R.id.update:
//                File file = GetandSaveCurrentImage();
//                EditText textView = new EditText(this);
//                AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                builder.setTitle("确认");
//                builder.setView(textView);
//                builder.setMessage("请输入标识码");
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Call<ResponseBody> call;
//
//                                RequestBody requestFile = RequestBody.create(MediaType.parse("form-data"), file);
//                                //中文文件名问题，服务端本地化的时候记得解码
//                                String encodeName = null;
//                                try {
//                                    encodeName = URLEncoder.encode(file.getName(), "UTF-8");
//                                } catch (UnsupportedEncodingException e) {
//                                    e.printStackTrace();
//                                }
//                                MultipartBody.Part body = MultipartBody.Part.createFormData("file", encodeName, requestFile);
//
//                                String gamename = "";
//                                if (gamename.equals("ty")) gamename = "跳远";
//                                else if (gamename.equals("qq")) gamename = "铅球";
////                                call = NetWorkManager.getRequest().upMonitor(resultValue.getText().toString(), gamename, textView.getEditableText().toString(), body);
////                                try {
////                                    Response<ResponseBody> response = call.execute();
////                                    String url = response.body().string();
////                                    String mFileUrl = NetWorkManager.retrofit.baseUrl() + url;
////                                    download(mFileUrl);
////                                } catch (IOException e) {
////                                    e.printStackTrace();
////                                }
//                            }
//                        }).start();
//                    }
//                });
//                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//
//                    }
//                });
//                builder.show();
//                break;
        }

    }

    SimpleDateFormat f1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); //其中没有些格式化参数，我们使用默认的日期格式。

    private File GetandSaveCurrentImage() {
        File file;
        //1.构建Bitmap
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        //2.获取屏幕
        View decorview = this.getWindow().getDecorView();
        decorview.destroyDrawingCache();
        decorview.setDrawingCacheEnabled(true);
        decorview.buildDrawingCache();
        bmp = decorview.getDrawingCache();
        String SavePath = getSDCardPath() + "/AndyDemo/ScreenImage";
        //3.保存Bitmap
        try {
            File path = new File(SavePath);
            //文件
            String filepath = SavePath + "/Screen_1.png";
            file = new File(filepath);
            if (!path.exists()) {
                path.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                Toast.makeText(getBaseContext(), "截屏文件已保存至SDCard/AndyDemo/ScreenImage/下", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return file;
    }


    /**
     * 获取SDCard的目录路径功能
     *
     * @return
     */

    private String getSDCardPath() {
        File sdcardDir = null;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdcardExist) {
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //22上键
        if (keyCode == 22) {
            TotalStationManager.getInstance().changeLASER_POINTER();
        }
        //22下键
        if (keyCode == 21) {
            TotalStationManager.getInstance().changeLASER_PLUMMET();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void newAngle(Double angel) {
        runOnUiThread(() -> {
            hr_value.setText(AngleUtils.changeToDFMArray(angel));
            if (!aisconfirm) ahr_value.setText(AngleUtils.changeToDFMArray(angel));
            if (!bisconfirm) bhr_value.setText(AngleUtils.changeToDFMArray(angel));
        });

    }

    @Override
    public void newDistance(Double distance) {

    }
}
